<template>
  <div class="container">
    <!-- 搜索区域 -->
    <div class="search-area">
      <el-input
        style="width: 300px; margin-left: 10px"
        v-model="input7"
        placeholder="请输入用户id"
      ></el-input>
      <el-input
        style="width: 300px; margin-left: 10px"
        v-model="input8"
        placeholder="请输入商品id"
      ></el-input>
      <el-button
        class="annu"
        type="primary"
        icon="el-icon-search"
        @click="searchData"
        >查找</el-button
      >
      <el-button
        class="annu2"
        type="primary"
        icon="el-icon-download"
        @click="exportData"
        >导出</el-button
      >
    </div>
    <!-- 表格区域 -->
    <div class="table-wrapper">
      <el-table
        :data="list"
        highlight-current-row
        border
        style="width: 100%"
        :row-class-name="tableRowClassName"
        :key="page + '-' + limit"
        @sort-change="handleSortChange"
      >
        <el-table-column
          fixed
          prop="id"
          label="收藏id"
          width="117.5"
          sortable="custom"
        >
        </el-table-column>
        <el-table-column prop="userId" label="用户id"> </el-table-column>
        <el-table-column prop="goodsId" label="商品id"> </el-table-column>
        <el-table-column prop="updateTime" label="添加时间"> </el-table-column>
      </el-table>
      <div v-if="list.length === 0" style="text-align: center; padding: 20px">
        暂无数据
      </div>
    </div>
    <!-- 分页区域 -->
    <div class="block" style="margin-top: 20px">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="page"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="limit"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </div>
    <!-- 详情弹框 -->
    <el-dialog :visible.sync="dialogVisible" title="用户详情" width="30%">
      <p>用户名</p>
      <el-input
        v-model="selectedUser.nickname"
        placeholder="请输入内容"
      ></el-input>
      <p>用户手机</p>
      <el-input
        v-model="selectedUser.mobile"
        placeholder="请输入内容"
      ></el-input>
      <p>用户性别</p>
      <el-select v-model="selectedUser.gender" placeholder="请选择性别">
        <el-option
          v-for="option in genderOptions"
          :key="option.value"
          :label="option.label"
          :value="option.value"
        >
        </el-option>
      </el-select>
      <p>用户等级</p>
      <el-select v-model="selectedUser.userLevel" placeholder="请选择用户等级">
        <el-option
          v-for="option in userLevelOptions"
          :key="option.value"
          :label="option.label"
          :value="option.value"
        >
        </el-option>
      </el-select>
      <p>用户状态</p>
      <el-select v-model="selectedUser.status" placeholder="请选择用户状态">
        <el-option
          v-for="option in statusOptions"
          :key="option.value"
          :label="option.label"
          :value="option.value"
        >
        </el-option>
      </el-select>
      <template #content>
        <div></div>
      </template>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button @click="queding">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { huiyuanzuiji, getUserById } from "@/api/yonghuguanli/huiyuanzuji.js";
import dayjs from "dayjs";

export default {
  data() {
    return {
      input7: "",
      input8: "",
      list: [],
      page: 1,
      limit: 20,
      total: 0,
      sort: "add_time",
      order: "desc",
      token: "your_token_here",
      dialogVisible: false,
      selectedUser: {},
      genderOptions: [
        { value: 1, label: "男" },
        { value: 2, label: "女" },
        { value: 3, label: "未知" },
      ],
      userLevelOptions: [
        { value: 0, label: "普通用户" },
        { value: 1, label: "VIP用户" },
        { value: 2, label: "高级用户" },
      ],
      statusOptions: [
        { value: 0, label: "可用" },
        { value: 1, label: "禁用" },
        { value: 2, label: "注销" },
      ],
    };
  },
  created() {
    this.fetchData();
  },
  mounted() {
    const params = {
      userId: this.input7,
      goodsId: this.input8,
      page: this.page,
      limit: this.limit,
      sort: this.sort,
      order: this.order,
      token: this.token,
    };
    huiyuanzuiji(params)
      .then((res) => {
        console.log("huiyuanzuiji 请求响应:", res);
        if (res.data && Array.isArray(res.data.list)) {
          const formattedList = res.data.list.map((item) => {
            return {
              ...item,
              addTime: dayjs(item.addTime).format("YYYY-MM-DD HH:mm:ss"),
              lastLoginTime: dayjs(item.lastLoginTime).format(
                "YYYY-MM-DD HH:mm:ss"
              ),
              updateTime: dayjs(item.updateTime).format("YYYY-MM-DD HH:mm:ss"),
            };
          });
          this.list = formattedList;
          this.total = res.data.total;
        } else {
          console.error("huiyuanzuiji 接口返回的数据格式不符合预期", res.data);
        }
      })
      .catch((error) => {
        console.error("huiyuanzuiji 请求出错:", error);
      });
  },
  methods: {
    showDetail(row) {
      console.log("点击行的数据:", row);
      const formattedUser = {
        ...row,
        addTime: dayjs(row.addTime).format("YYYY-MM-DD HH:mm:ss"),
        lastLoginTime: dayjs(row.lastLoginTime).format("YYYY-MM-DD HH:mm:ss"),
        updateTime: dayjs(row.updateTime).format("YYYY-MM-DD HH:mm:ss"),
      };
      this.selectedUser = formattedUser;
      this.dialogVisible = true;
    },
    // 重置
    reset() {
      this.input7 = "";
      this.input8 = "";
      this.page = 1;
      this.fetchData();
    },
    // 搜索数据
    searchData() {
      if (this.input7) {
        this.getUserById();
      } else {
        this.page = 1;
        this.fetchData();
      }
    },
    async fetchData() {
      const params = {
        userId: this.input7,
        goodsId: this.input8,
        page: this.page,
        limit: this.limit,
        sort: this.sort,
        order: this.order,
        token: this.token,
      };
      console.log("请求参数:", params);
      try {
        const res = await huiyuanzuiji(params);
        console.log("huiyuanzuiji 请求响应:", res);
        if (res.data && Array.isArray(res.data.list)) {
          const formattedList = res.data.list.map((item) => {
            return {
              ...item,
              addTime: dayjs(item.addTime).format("YYYY-MM-DD HH:mm:ss"),
              lastLoginTime: dayjs(item.lastLoginTime).format(
                "YYYY-MM-DD HH:mm:ss"
              ),
              updateTime: dayjs(item.updateTime).format("YYYY-MM-DD HH:mm:ss"),
            };
          });
          this.list = formattedList;
          this.total = res.data.total;
        } else {
          console.error("huiyuanzuiji 接口返回的数据格式不符合预期", res.data);
        }
      } catch (error) {
        console.error("数据请求出错:", error);
      }
    },
    async getUserById() {
      if (typeof getUserById !== "function") {
        console.error("getUserById 不是一个函数，请检查 API 引入和导出");
        return;
      }
      const params = {
        userId: parseInt(this.input7, 10),
      };
      console.log("根据 id 搜索的请求参数:", params);
      console.log("传递的 id 值:", this.input7);
      try {
        const res = await getUserById(params);
        console.log("getUserById 请求响应:", res);
        if (res.data) {
          let formattedList;
          if (Array.isArray(res.data.list)) {
            formattedList = res.data.list.map((item) => {
              return {
                ...item,
                addTime: dayjs(item.addTime).format("YYYY-MM-DD HH:mm:ss"),
                lastLoginTime: dayjs(item.lastLoginTime).format(
                  "YYYY-MM-DD HH:mm:ss"
                ),
                updateTime: dayjs(item.updateTime).format(
                  "YYYY-MM-DD HH:mm:ss"
                ),
              };
            });
          } else {
            formattedList = [res.data].map((item) => {
              return {
                ...item,
                addTime: dayjs(item.addTime).format("YYYY-MM-DD HH:mm:ss"),
                lastLoginTime: dayjs(item.lastLoginTime).format(
                  "YYYY-MM-DD HH:mm:ss"
                ),
                updateTime: dayjs(item.updateTime).format(
                  "YYYY-MM-DD HH:mm:ss"
                ),
              };
            });
          }
          this.list = formattedList;
          this.total = formattedList.length;
        } else {
          console.error("getUserById 接口返回的数据格式不符合预期", res.data);
        }
      } catch (error) {
        console.error("根据 id 搜索数据出错:", error);
      }
    },
    tableRowClassName({ row, rowIndex }) {
      return rowIndex % 2 === 1 ? "dark-row" : "";
    },
    handleSizeChange(newLimit) {
      this.limit = newLimit;
      this.fetchData();
    },
    handleCurrentChange(newPage) {
      this.page = newPage;
      this.fetchData();
    },
    async queding() {
      try {
        const { id, nickname, mobile, gender, userLevel, status } =
          this.selectedUser;
        const params = {
          id,
          nickname,
          mobile,
          gender,
          userLevel,
          status,
          token: this.token,
        };

        const res = await bianji(params);
        console.log("编辑用户信息响应:", res);
        if (res.data && res.data.code === 200) {
          this.$message.success("用户信息更新成功");
          this.dialogVisible = false;
          this.fetchData();
        } else {
          this.$message.error("用户信息更新失败");
        }
      } catch (error) {
        console.error("编辑用户信息出错:", error);
        this.$message.error("编辑用户信息出错");
      }
    },
    exportData() {
      if (this.list.length === 0) {
        this.$message.warning("暂无数据可导出");
        return;
      }

      const headers = ["收藏id", "用户id", "商品id", "添加时间"];
      const csvContent = [headers.join(",")];

      this.list.forEach((item) => {
        const row = [
          item.id,
          item.userId,
          item.goodsId,
          dayjs(item.updateTime).format("YYYY-MM-DD HH:mm:ss"),
        ];
        csvContent.push(row.join(","));
      });

      const csvBlob = new Blob([csvContent.join("\n")], {
        type: "text/csv;charset=utf-8;",
      });
      const csvUrl = URL.createObjectURL(csvBlob);
      const link = document.createElement("a");
      link.href = csvUrl;
      link.setAttribute("download", "用户数据.csv");
      link.click();
      URL.revokeObjectURL(csvUrl);
    },
    handleSortChange({ column, prop, order }) {
      if (prop === "id") {
        this.sort = "id";
        this.order = order === "ascending" ? "asc" : "desc";
        this.page = 1;
        this.fetchData();
      }
    },
  },
};
</script>

<style scoped>
.el-table .warning-row {
  background: oldlace;
}

.el-table .success-row {
  background: #f0f9eb;
}

.container {
  display: flex;
  flex-direction: column;
  padding: 10px;
}
.search-area {
  display: flex;
  align-items: center;
  padding-bottom: 10px;
}

.el-input--small .el-input__inner {
  height: 47px;
  line-height: 32px;
}

.table-wrapper {
  flex: 1;
  overflow-y: auto;
}

.el-button--small {
  padding: 14px 36px;
  font-size: 12px;
  border-radius: 3px;
}

.pagination-area {
  padding: 10px 0;
  display: flex;
  justify-content: flex-end;
}

.el-input__inner {
  height: 50px;
  line-height: 50px;
}

.dark-row {
  background-color: #f5f5f5;
}

.cell {
  font-size: 18px;
}
.archive-button {
  background-color: #fff;
  color: #f56c6c;
  border: 1px solid #f56c6c;
  padding: 6px 12px;
  border-radius: 4px;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s;
}

.archive-button:hover {
  background-color: #f56c6c;
  color: #fff;
}
</style>